package guda.house.biz.impl;

import guda.house.biz.TaskStatBiz;
import guda.house.biz.bo.EstateFeeBO;
import guda.house.biz.bo.ParkingFeeBO;
import guda.house.biz.query.BillPayQuery;
import guda.house.biz.query.SmsQuery;
import guda.house.biz.query.VillageQuery;
import guda.house.biz.util.PriceUtil;
import guda.house.biz.util.SmsUtil;
import guda.house.biz.util.Transform;
import guda.house.biz.util.TransformHelper;
import guda.house.dal.dao.*;
import guda.house.dal.dataobject.BillPayDO;
import guda.house.dal.dataobject.SmsDO;
import guda.house.dal.dataobject.VillageDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by well on 16/1/24.
 */
public class TaskStatBizImpl implements TaskStatBiz,InitializingBean{

    private final static Logger logger = LoggerFactory.getLogger(TaskStatBizImpl.class);

    @Autowired
    private EstateFeeBO estateFeeBO;
    @Autowired
    private ParkingFeeBO parkingFeeBO;
    @Autowired
    private VillageDAO villageDAO;

    @Autowired
    private SmsDAO smsDAO;
    @Autowired
    private BillPayDAO billPayDAO;
    @Autowired
    private BillElecDAO billElecDAO;
    @Autowired
    private BillEstateDAO billEstateDAO;
    @Autowired
    private BillWaterDAO billWaterDAO;
    @Autowired
    private BillParkingDAO billParkingDAO;
    @Autowired
    private BillExtDAO billExtDAO;




    @Override
    public void stat() {

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Runnable runnable = new Runnable() {
            public void run() {
                try {
                    VillageQuery villageQuery = new VillageQuery();
                    villageQuery.setPageSize(100);
                    List<VillageDO> villageDOs = villageDAO.selectForPage(villageQuery);
                    for (VillageDO villageDO : villageDOs) {
                        estateFeeBO.stateFee(villageDO.getVillageId());
                    }
                    for (VillageDO villageDO : villageDOs) {
                        parkingFeeBO.stateFee(villageDO.getVillageId());
                    }
                }catch (Exception e){
                    logger.error("",e);
                }
            }
        };
        ScheduledExecutorService service = Executors
                .newSingleThreadScheduledExecutor();
        // 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
        service.scheduleAtFixedRate(runnable, 1, 6, TimeUnit.HOURS);



//        Runnable runnableSms = new Runnable() {
//            public void run() {
//                statSms();
//            }
//        };
//
//        long oneDay = 24 * 60 * 60 * 1000;
//        long initDelay  = getTimeMillis("19:00:00") - System.currentTimeMillis();
//        initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
//        service.scheduleAtFixedRate(
//                runnableSms,
//                initDelay,
//                oneDay,
//                TimeUnit.MILLISECONDS);

    }

    private static long getTimeMillis(String time) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
            Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
            return curDate.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private void statSms(){
        try{
            //定时统计并发送短信
            SmsQuery smsQuery = new SmsQuery();
            smsQuery.setPageSize(1000);
            List<SmsDO> smsDOs = smsDAO.selectForPage(smsQuery);
            for(SmsDO smsDO:smsDOs){
                if(StringUtils.hasText(smsDO.getPhoneArray())){

                    BillPayQuery billPayQuery = new BillPayQuery();
                    billPayQuery.setVillageId(smsDO.getVillageId());
                    billPayQuery.setEndDate(getDayEnd());
                    billPayQuery.setStartDate(getDayStart());
                    billPayQuery.setPageSize(10000);
                    List<BillPayDO> billPayDOs = billPayDAO.selectForPayedLog(billPayQuery);
                    StringBuilder buff = new StringBuilder();
                    buff.append("小区［").append(villageDAO.getVillageById(smsDO.getVillageId()).getVillageName());
                    long total = 0;
                    List<Long> billPayIdList = new ArrayList<Long>(billPayDOs.size());
                    for(BillPayDO billPayDO:billPayDOs){
                        total+=billPayDO.getPayTotal();
                        billPayIdList.add(billPayDO.getPayId());
                    }
                    buff.append("］今日共收费：").append(PriceUtil.formatCNY(total)).append("元。");

                    if(billPayIdList.size() == 0){
                        SmsUtil.sendSms(smsDO.getPhoneArray(),buff.toString());
                        continue;
                    }
                    buff.append("分别如下:");
                    Long aLong = billEstateDAO.statPaidBill(billPayIdList);
                    if(aLong!=null){
                        buff.append("物业费:").append(PriceUtil.formatCNY(aLong)).append("元。");
                    }else{
                        buff.append("物业费:0元。");
                    }

                    Long aLongWater = billWaterDAO.statPaidBill(billPayIdList);
                    if(aLongWater!=null){
                        buff.append("水费:").append(PriceUtil.formatCNY(aLongWater)).append("元。");
                    }else{
                        buff.append("水费:0元。");
                    }

                    Long aLongElec = billElecDAO.statPaidBill(billPayIdList);
                    if(aLongElec!=null){
                        buff.append("电费:").append(PriceUtil.formatCNY(aLongElec)).append("元。");
                    }else{
                        buff.append("电费:0元。");
                    }

                    Long aLongParking = billParkingDAO.statPaidBill(billPayIdList);
                    if(aLongParking!=null){
                        buff.append("车位费:").append(PriceUtil.formatCNY(aLongParking)).append("元。");
                    }else{
                        buff.append("车位费:0元。");
                    }

                    Long aLongExt = billExtDAO.statPaidBill(billPayIdList);
                    if(aLongExt!=null){
                        buff.append("其他费用:").append(PriceUtil.formatCNY(aLongExt)).append("元。");
                    }else{
                        buff.append("其他费用:0元。");
                    }

                    SmsUtil.sendSms(smsDO.getPhoneArray(),buff.toString());
                }
            }
        }catch(Exception e){
            logger.error("",e);
        }
    }


    public static Date getDayStart(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }


    public static Date getDayEnd(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }


}
